package org.itboys.mobile.service.mysql.mobile.product;

import org.itboys.admin.dto.lasted.SundayUploadDto;
import org.itboys.admin.entity.lasted.SystemDictionary;
import org.itboys.admin.service.lasted.SundayUploadService;
import org.itboys.admin.service.lasted.SystemDictionaryService;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.kitchen.entity.mongo.village.KitchenVillage;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dto.SundayCommentDto;
import org.itboys.mobile.dto.product.SundayProductDto;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.mongo.SundayPermission;
import org.itboys.mobile.entity.mysql.product.SundayProduct;
import org.itboys.mobile.service.mongo.mobile.KitchenMobileVillageService;
import org.itboys.mobile.service.mongo.mobile.SundayMobileCommentService;
import org.itboys.mobile.service.mongo.mobile.SundayMobilePermissionService;
import org.itboys.mobile.service.mongo.mobile.collection.SundayMobileCollectionService;
import org.itboys.mobile.service.mongo.mobile.product.KitchenMobileProductCookBookService;
import org.itboys.mobile.service.mongo.web.SundayMemberService;
import org.itboys.mongodb.service.BaseMySqlService;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.security.provider.Sun;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：圣代_商品_service_mobile
 */
@Service
public class SundayMobileProductService extends BaseMySqlService<SundayProduct> {
    @Autowired
    private SundayMemberService memberService;
    @Autowired
    private SundayUploadService uploadService;
    @Autowired
    private SundayMobileCollectionService collectionService;
    @Autowired
    private ResourceHolder resourceHolder;
    @Autowired
    private SundayMobileCommentService commentService;
    @Autowired
    private KitchenMobileProductCookBookService productCookBookService;
    @Autowired
    private SundayMobilePermissionService permissionService;
    @Autowired
    private KitchenMobileVillageService villageService;
    @Autowired
    private SystemDictionaryService dictionaryService;

    /**
     * 分页获取商品
     * @param request
     * @param memberId
     * @param type 1商城商品。2积分商品，3采购商品
     */
    public List<SundayProductDto> selectProduct2(HttpServletRequest request,Long memberId,Long villageId,Integer type){

       List<SundayProduct> products =getShopProduct(request,
                null,
                type,
               null,
                memberId,
                null,
                villageId,true);
        return packageDtoMuilt(products);
    }
    /**
     * 查询商品详情
     * @param memberId
     * @param productId
     * @param villageId
     */
    public SundayProductDto findOne(Long memberId,Long productId,Long villageId){
        SundayProduct product =super.find(productId);
        product=getShopProduct(null,
                null,
                product.getType(),
                product,
                memberId,
                null,
                 villageId,false).get(0);
        //推荐商品
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("categoryId",product.getCategoryId());
        param.put("status",1);
        param.put("row_start",0);
        param.put("row_size",2);
        param.put("type",product.getType());
        List<SundayProduct> recProducts =getShopProduct(null,
                param,
                product.getType(),
                null,
                memberId,
                null,
                villageId,true);

        List<Map<String,Object>> recommendProducts = new ArrayList<>();
       for(SundayProductDto productDto:packageDtoMuilt(recProducts)){
            Map<String,Object> reProduct = new HashMap<String,Object>();
            reProduct.put("id",productDto.getId());
            reProduct.put("name",productDto.getName());
            reProduct.put("viceName",productDto.getViceName());
            reProduct.put("image",productDto.getImage());
            reProduct.put("price",productDto.getPrice());
            reProduct.put("marketPrice",productDto.getMarketPrice());
            recommendProducts.add(reProduct);
        }
        return packageDtoSingle(product,memberId,recommendProducts);

    }
    /**
     * 查询商品详情(分享时使用)

     * @param productId

     */
    public SundayProduct share(Long productId){
        SundayProduct product =super.find(productId);
        //加载轮播图
        List<SundayUploadDto> rollImages = uploadService.selectNoPage(productId,SundayProduct.class.getSimpleName());
        product.setRollImages(rollImages);
        return product;

    }
    /** 组装DTO
     * 不同的用户类型。商品价格享受价格不同
     * 1，普通用户。零售价格
     * 2，门店。批发价格
     * 3，大客户。折扣价格
     *
     */
    public SundayProductDto packageDtoSingle(SundayProduct product, Long memberId,List<Map<String,Object>> recommendProducts){

        SundayProductDto dto = null;
        //静态资源


        //组装轮播图
        List<SundayUploadDto> rollImages = uploadService.selectNoPage(product.getId(),SundayProduct.class.getSimpleName());
        //商品详情URL
        String descUrl =resourceHolder.getStringValue("mobileRoot")+"/sunday/mobile/product/desc?id="+product.getId();
        //判断受否收藏
        Integer isCollection =collectionService.checkIsCollection(memberId,SundayCommonConstants.collection_type_product,product.getId());
        //加载默认评论
        logger.info("加载评论");
        List<SundayCommentDto> comments = commentService.getCommentByNumber(2,product.getId(),SundayProduct.class.getSimpleName());
        logger.info("加载评论-结束");
        //List<SundayCommentDto> comments =null;
        //加载推荐商品

        dto=  new SundayProductDto(product.getId(), product.getCreateTime(), product.getCreateDate(),
                product.getName()+product.getStandard(), product.getNumber(), product.getViceName(),   product.getStandard(),  product.getMarketPrice(), product.getPrice(),  product.getType(),
                product.getImage(),  product.getSaleNumber(), rollImages,  product.getCostPrice(),
                isCollection,  descUrl,  recommendProducts, comments,product.getStore(),product.getItemCode());
        //分享地址
        dto.setShareUrl(resourceHolder.getStringValue("mobileRoot")+"/sunday/mobile/product/share?id="+product.getId());
        dto.setShareImage(product.getImage());
        dto.setShareTitle("花果山果蔬 产品分享");
        dto.setShareDesc(product.getName()+product.getViceName()+product.getStandard());

        //加载关联菜谱
        List<Map<String,Object>> cookBooks = productCookBookService.getCookBooksByProduct(product.getId());
        dto.setCookBooks(cookBooks);

        return dto;
    }

    /**
     * 组装商品DTO
     * @param products
     * @return
     */
    public List<SundayProductDto> packageDtoMuilt(List<SundayProduct> products){
        String imageRoot = resourceHolder.getStringValue("imgRoot");
        List<SundayProductDto> dtos = new ArrayList<SundayProductDto>();
        for(SundayProduct product:products){
            //主图
            dtos.add(
                    new SundayProductDto(product.getId(), product.getCreateTime(), product.getCreateDate(),
                    product.getName()+product.getStandard(),  product.getViceName(),   product.getStandard(),  product.getMarketPrice(), product.getPrice(),  product.getType(),
                    imageRoot+product.getImage(),  product.getSaleNumber(),  product.getCostPrice(),product.getStore(),product.getNumber(),product.getItemCode()));

        }
       return dtos;
    }

    /**
     * 根据门店获取商品，并且匹配门店价格和库存
     * @param request
     * @param param 商品查询参数
     * @param productType 商品类型
     * @param product 商品 详情
     * @param memberId 用户ID
     * @param productIds 用户
     * @param villageId 小区ID
     * @param isCheckStore 是否校验库存。将库存不满足要求商品。列表true,详情false
     * @return
     */
    public List<SundayProduct> getShopProduct(HttpServletRequest request,
                                              Map<String,Object> param,
                                              Integer productType,
                                              SundayProduct product,
                                              Long memberId,
                                              List<Long> productIds,
                                              Long villageId,boolean isCheckStore) {
        //返回价格
        List<SundayProduct> resultProducts = new ArrayList<SundayProduct>();
        //查询商品参数
        if(request==null){
            if(param==null){
                param=new HashMap<String,Object>();
            }
        }else{
            param=ParamUtil.packageMysqlPageParam(request,"name","categoryId");
        }
        //用户
       // if(member==null){
        SundayMember  member=memberService.getById(memberId);
        //}
        //获取商品类型。1商城，2积分，3采购（也是商城商品，但是可以用用户类型判断）
        if(productType==3){
            //采购商品也是商城商品
            param.put("type",1);
        }else{
            param.put("type",productType);
        }
        //查询门店的库存和价格；

        List<SundayPermission> permissions = new ArrayList<SundayPermission>();
        //List<Long> productIds = new ArrayList<Long>();
        logger.info("Aa");
        if(member.getUserType()==SundayCommonConstants.user_type_member&&
                productType==SundayCommonConstants.type_mall){
            logger.info("A2");


            KitchenVillage village = villageService.getById(villageId);


           Map<String,Object> permissionParam=new HashMap<String,Object>();
            permissionParam.put("memberId", village.getShopId());
            permissionParam.put("isDeleted", 0);
            if(isCheckStore){
                permissionParam.put("store >=",Integer.valueOf(dictionaryService.getDictionaryByKey2("minimumStore").getValue()));
            }
            //商品详情是传入商品ID
            if(product!=null){
                permissionParam.put("productId",product.getId());
            }
            //购物车传入商品ID集合
            if(ListUtil.isNotNull(productIds)){
                permissionParam.put("productId in",productIds);
            }else{
                productIds= new ArrayList<Long>();
            }
            permissions=permissionService.list(permissionParam);
            if(ListUtil.isNull(permissions)){
                return resultProducts;
            }
            for(SundayPermission permission:permissions){

                productIds.add(permission.getProductId());
            }
        }
        param.put("ids",productIds);
        //只查询上架的
        param.put("status",1);
        //商品列表
        if(product==null){
            logger.info("AA");
            resultProducts=super.select(param);
            //商品详情
            for(SundayProduct p:resultProducts){
                logger.info("mar="+p.getMarketPrice()+",price"+p.getPrice());
            }
        }else{
            logger.info("BB");
            resultProducts.add(product);
        }

        if(ListUtil.isNull(resultProducts)){
            logger.info("EE");
            return resultProducts;
        }
        //匹配门店价格和库存
        if(ListUtil.isNotNull(permissions)&&member.getUserType()==SundayCommonConstants.user_type_member){
            logger.info("HHH");

                for(SundayProduct resultProduct:resultProducts){
                    for(SundayPermission permission:permissions) {
                        if (LongUtil.isNotZreo(permission.getProductId()) &&
                                resultProduct.getId().longValue() == permission.getProductId().longValue()) {
                            //匹配价格和库存
                            resultProduct.setPrice(new BigDecimal(permission.getPrice()).setScale(2, BigDecimal.ROUND_HALF_UP));
                            resultProduct.setStore(permission.getStore());
                            break;
                        }
                    }
                }
        }
        return resultProducts;
    }
}
